//
//  UserViewController.m
//  Final
//
//  Created by Lenrony on 2021/12/2.
//  Copyright © 2021 Lenrony. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "UserViewController.h"
#import "UserDetailViewController.h"
#import "MyArticlesViewController.h"
#import "ReceivedCommentsViewController.h"
#import "ReceivedSupportsViewController.h"
#import "../ModelController.h"

@interface UserViewController(){
    float screen_width;
    float screen_height;
}

@property (nonatomic) BOOL logStatus;

@property (strong,nonatomic) UIImageView *imageView;
@property (strong,nonatomic) UILabel *mailLabel;
@property (strong,nonatomic) UILabel *passwordLabel;
@property (strong,nonatomic) UITextField *mailTextField;
@property (strong,nonatomic) UITextField *passwordTextField;
@property (strong,nonatomic) UILabel *mailcheck;
@property (strong,nonatomic) UILabel *passwordcheck;
@property (strong,nonatomic) UIButton *registerBtn;
@property (strong,nonatomic) UIButton *loginBtn;
@property (strong,nonatomic) UIAlertController* alert;

@property (nonatomic) BOOL isUidValid;
@property (nonatomic) BOOL isPasswordValid;

@property (strong,nonatomic) UIImageView* headImgView;
@property (strong,nonatomic) UILabel* uidLabel;
@property (strong,nonatomic) UILabel* nameLabel;
@property (strong,nonatomic) UIButton* myDetailBtn;
@property (strong,nonatomic) UIButton* myArticleBtn;
@property (strong,nonatomic) UIButton* myCommentBtn;
@property (strong,nonatomic) UIButton* mySupportBtn;
@property (strong,nonatomic) UIButton* logoutBtn;

@property (strong,nonatomic) ModelController* mc;
//@property (strong,nonatomic) NSUserDefaults* userDefaults;

@end

@implementation UserViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    screen_width = self.view.bounds.size.width;
    screen_height = self.view.bounds.size.height;
    
    self.logStatus = false;
    self.mc = [ModelController getInstance];
}

- (void)viewWillAppear:(BOOL)animated
{
    if([[NSUserDefaults standardUserDefaults] objectForKey:@"u_id"] && [[NSUserDefaults standardUserDefaults] objectForKey:@"password"]) {
        int check = [self.mc signIn:[[NSUserDefaults standardUserDefaults] objectForKey:@"u_id"] andPassword:[[NSUserDefaults standardUserDefaults] objectForKey:@"password"]];
        if (check==0) { }
        else if (check==1) {
            _mailcheck.text = @"用户不存在";
            [self showAlertWithTitle:@"登录失败" andText:@"用户名不存在！"];
        }
        else {
            _passwordcheck.text = @"密码错误";
            [self showAlertWithTitle:@"登录失败" andText:@"密码错误！"];
        }
    }
    
    if(self.mc.cur_user == nil){
        [self loadLoginView];
        self.isUidValid = false;
        self.isPasswordValid = false;
    }
    else{
        [self loadUserView];
    }
}

-(void)loadLoginView
{
    if(self.logStatus){
        self.logStatus = false;
        [self.headImgView removeFromSuperview];
        [self.uidLabel removeFromSuperview];
        [self.nameLabel removeFromSuperview];
        [self.myDetailBtn removeFromSuperview];
        [self.myArticleBtn removeFromSuperview];
        [self.myCommentBtn removeFromSuperview];
        [self.mySupportBtn removeFromSuperview];
        [self.logoutBtn removeFromSuperview];
    }
    [self.view addSubview: self.imageView];
    [self.view addSubview: self.mailLabel];
    [self.view addSubview: self.passwordLabel];
    [self.view addSubview: self.mailTextField];
    [self.view addSubview: self.passwordTextField];
    [self.view addSubview: self.mailcheck];
    [self.view addSubview: self.passwordcheck];
    [self.view addSubview: self.registerBtn];
    [self.view addSubview: self.loginBtn];
    
    self.mailTextField.text = @"";
    self.passwordTextField.text = @"";
}

-(void)loadUserView
{
    if(!self.logStatus){
        self.logStatus = true;
        [self.imageView removeFromSuperview];
        [self.mailLabel removeFromSuperview];
        [self.passwordLabel removeFromSuperview];
        [self.mailTextField removeFromSuperview];
        [self.passwordTextField removeFromSuperview];
        [self.mailcheck removeFromSuperview];
        [self.passwordcheck removeFromSuperview];
        [self.registerBtn removeFromSuperview];
        [self.loginBtn removeFromSuperview];
    }
    [self.view addSubview: self.headImgView];
    [self.view addSubview: self.uidLabel];
    [self.view addSubview: self.nameLabel];
    [self.view addSubview: self.myDetailBtn];
    [self.view addSubview: self.myArticleBtn];
    [self.view addSubview: self.myCommentBtn];
    [self.view addSubview: self.mySupportBtn];
    [self.view addSubview: self.logoutBtn];
    
    self.headImgView.image = self.mc.cur_user.head_img;
    self.uidLabel.text = [NSString stringWithFormat:@"UID: %@", self.mc.cur_user.u_id];
    if([self.mc.cur_user.name isEqualToString:@""]){
        self.nameLabel.text = @"Anonymous";
    }
    else{
        self.nameLabel.text = self.mc.cur_user.name;
    }
}

- (void)btnClickRegister:(id)sender {
    if(!self.isUidValid || !self.isPasswordValid){
        [self showAlertWithTitle:@"注册失败" andText:@"用户名和密码格式不合法！"];
        return;
    }
    int check = [self.mc regist:_mailTextField.text andPassword:_passwordTextField.text];
    if(check==0){
        [self showAlertWithTitle:@"注册成功" andText:@"可以直接登录！"];
    }
    else{
        _mailcheck.text = @"用户已存在";
        [self showAlertWithTitle:@"注册失败" andText:@"用户已存在！"];
    }
}

- (void)btnClickLogin:(id)sender {
    if(!self.isUidValid || !self.isPasswordValid){
        [self showAlertWithTitle:@"登录失败" andText:@"用户名和密码格式不合法！"];
        return;
    }
    int check = [self.mc signIn:_mailTextField.text andPassword:_passwordTextField.text];
    if(check==0){
        [self showAlertWithTitle:@"登录成功" andText:@"即将跳转到个人页面！"];
//        self.userDefaults = [NSUserDefaults standardUserDefaults];
        [[NSUserDefaults standardUserDefaults] setObject:self.mc.cur_user.u_id forKey:@"u_id"];
        [[NSUserDefaults standardUserDefaults] setObject:self.mc.cur_user.password forKey:@"password"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }
    else if(check==1){
        _mailcheck.text = @"用户不存在";
        [self showAlertWithTitle:@"登录失败" andText:@"用户名不存在！"];
    }
    else{
        _passwordcheck.text = @"密码错误";
        [self showAlertWithTitle:@"登录失败" andText:@"密码错误！"];
    }
}

- (void)mailTextFieldDidChange:(id)sender {
    NSString *emailRegex = @"^[1-9]{1}+[0-9]{7}+$";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    self.isUidValid = [emailTest evaluateWithObject:_mailTextField.text];
    if(self.isUidValid){
        _mailcheck.text = @"";
    }
    else{
        _mailcheck.text = @"学号8位数字,不以0开头";
    }
}

- (void)passwordTextFieldDidChange:(id)sender {
    NSString *passwordRegex = @"^[a-zA-Z0-9]{8,20}+$";
    NSPredicate *passwordTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", passwordRegex];
    self.isPasswordValid = [passwordTest evaluateWithObject:_passwordTextField.text];
    if(self.isPasswordValid){
        _passwordcheck.text = @"";
    }
    else{
        _passwordcheck.text = @"密码由数字字母组成，长度为8-20";
    }
}

- (void)showAlertWithTitle: (NSString*)title
                    andText: (NSString*)text
{
    self.alert = [UIAlertController alertControllerWithTitle:title message:text preferredStyle:UIAlertControllerStyleAlert];
    [self presentViewController:self.alert animated:YES completion:nil];
    [self performSelector:@selector(hideAlert) withObject:self.alert afterDelay:1.5];
}

- (void)hideAlert
{
    [self.alert dismissViewControllerAnimated:YES completion:^{
        if(self.mc.cur_user != nil){
            [self viewWillAppear:YES];
        }
    }];
}

-(void)goMyDetail
{
    NSLog(@"My Detail!");
    UserDetailViewController *udvc = [[UserDetailViewController alloc] initWithUser:self.mc.cur_user canBeModified:YES];
    [self.navigationController pushViewController:udvc animated:YES];
}

-(void)goMyArticle
{
    NSLog(@"My Article!");
    MyArticlesViewController *mavc = [[MyArticlesViewController alloc] init];
    [self.navigationController pushViewController:mavc animated:YES];
}

-(void)goMyComment
{
    NSLog(@"My Comment!");
    ReceivedCommentsViewController *rcvc = [[ReceivedCommentsViewController alloc] init];
    [self.navigationController pushViewController:rcvc animated:YES];
}

-(void)goMySupport
{
    NSLog(@"My Support!");
    ReceivedSupportsViewController *rsvc = [[ReceivedSupportsViewController alloc] init];
    [self.navigationController pushViewController:rsvc animated:YES];
}

-(void)logout
{
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"u_id"];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"password"];
    [self.mc signOut];
    [self viewWillAppear:YES];
}

//Lazy Load
-(UIImageView*) imageView
{
    if(_imageView == nil){
        _imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo.png"]];
        _imageView.frame = CGRectMake(self.view.frame.size.width/2-60, 150, 120, 120);
        _imageView.layer.cornerRadius = 10;
        _imageView.layer.masksToBounds = YES;
    }
    return _imageView;
}

-(UILabel*) mailLabel
{
    if(_mailLabel == nil){
        _mailLabel = [[UILabel alloc] init];
        _mailLabel.text = @"学号：";
        [_mailLabel setFont:[UIFont systemFontOfSize:21]];
        _mailLabel.frame = CGRectMake(40, 335, 65, 26);

    }
    return _mailLabel;
}

-(UILabel*) passwordLabel
{
    if(_passwordLabel == nil){
        _passwordLabel = [[UILabel alloc] init];
        _passwordLabel.text = @"密码：";
        [_passwordLabel setFont:[UIFont systemFontOfSize:21]];
        _passwordLabel.frame = CGRectMake(40, 408, 65, 26);
    }
    return _passwordLabel;
}

-(UITextField*) mailTextField
{
    if(_mailTextField == nil){
        _mailTextField = [[UITextField alloc] init];
        _mailTextField.autocorrectionType = UITextAutocorrectionTypeNo;
        [_mailTextField setPlaceholder:@" 请输入您的学号"];
        [_mailTextField setTextAlignment:NSTextAlignmentLeft];
        [_mailTextField setFont:[UIFont systemFontOfSize:18]];
        _mailTextField.frame = CGRectMake(112, 331, 223, 34);
        _mailTextField.layer.cornerRadius = 5;
        _mailTextField.layer.borderWidth = 1;
        _mailTextField.delegate = (id)self;
        [_mailTextField addTarget:self action:@selector(mailTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    return _mailTextField;
}

-(UITextField*) passwordTextField
{
    if(_passwordTextField == nil){
        _passwordTextField = [[UITextField alloc] init];
        _passwordTextField.secureTextEntry = YES;
        _passwordTextField.autocorrectionType = UITextAutocorrectionTypeNo;
        [_passwordTextField setPlaceholder:@" 请输入您的密码"];
        [_passwordTextField setTextAlignment:NSTextAlignmentLeft];
        [_passwordTextField setFont:[UIFont systemFontOfSize:18]];
        _passwordTextField.frame = CGRectMake(112, 404, 223, 34);
        _passwordTextField.layer.cornerRadius = 5;
        _passwordTextField.layer.borderWidth = 1;
        _passwordTextField.delegate = (id)self;
        [_passwordTextField addTarget:self action:@selector(passwordTextFieldDidChange:) forControlEvents:UIControlEventEditingChanged];
    }
    return _passwordTextField;
}

-(UILabel*) mailcheck
{
    if(_mailcheck == nil){
        _mailcheck = [[UILabel alloc] init];
        [_mailcheck setFont:[UIFont systemFontOfSize:15]];
        _mailcheck.frame = CGRectMake(112, 370, 300, 20);
        _mailcheck.textColor = [UIColor redColor];
    }
    return _mailcheck;
}

-(UILabel*) passwordcheck
{
    if(_passwordcheck == nil){
        _passwordcheck = [[UILabel alloc] init];
        [_passwordcheck setFont:[UIFont systemFontOfSize:15]];
        _passwordcheck.frame = CGRectMake(112, 443, 300, 20);
        _passwordcheck.textColor = [UIColor redColor];
    }
    return _passwordcheck;
}

-(UIButton*) registerBtn
{
    if(_registerBtn == nil){
        UIColor *btnColor= [UIColor colorWithRed:50/255.0 green:153/255.0 blue:50/255.0 alpha:1.0];
        _registerBtn = [[UIButton alloc] init];
        _registerBtn.frame = CGRectMake(self.view.frame.size.width/2-93, 505, 73, 40);
        [_registerBtn setBackgroundColor:btnColor];
        [_registerBtn setTitle:@"注册" forState:UIControlStateNormal];
        [_registerBtn setTintColor:[UIColor whiteColor]];
        _registerBtn.titleLabel.font = [UIFont systemFontOfSize:20];
        _registerBtn.layer.cornerRadius = 5;
        [_registerBtn addTarget:self action:@selector(btnClickRegister:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _registerBtn;
}

-(UIButton*) loginBtn
{
    if(_loginBtn == nil){
        UIColor *btnColor= [UIColor colorWithRed:50/255.0 green:153/255.0 blue:50/255.0 alpha:1.0];
        _loginBtn = [[UIButton alloc] init];
        _loginBtn.frame = CGRectMake(self.view.frame.size.width/2+20, 505, 73, 40);
        [_loginBtn setBackgroundColor:btnColor];
        [_loginBtn setTitle:@"登录" forState:UIControlStateNormal];
        [_loginBtn setTintColor:[UIColor whiteColor]];
        _loginBtn.titleLabel.font = [UIFont systemFontOfSize:20];
        _loginBtn.layer.cornerRadius = 5;
        [_loginBtn addTarget:self action:@selector(btnClickLogin:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginBtn;
}

-(UIImageView*) headImgView
{
    if(_headImgView == nil){
        _headImgView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo.png"]];
        _headImgView.frame = CGRectMake(self.view.frame.size.width/2-64, 130, 128, 128);
        _headImgView.layer.cornerRadius = 10;
        _headImgView.layer.masksToBounds = YES;
    }
    return _headImgView;
}

-(UILabel*) uidLabel
{
    if(_uidLabel == nil){
        _uidLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-100, 290, 200, 30)];
        [_uidLabel setFont:[UIFont systemFontOfSize:21]];
        _uidLabel.textAlignment = NSTextAlignmentCenter;
    }
    return _uidLabel;
}

-(UILabel*) nameLabel
{
    if(_nameLabel == nil){
        _nameLabel = [[UILabel alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-100, 330, 200, 30)];
        [_nameLabel setFont:[UIFont systemFontOfSize:21]];
        _nameLabel.textAlignment = NSTextAlignmentCenter;
        _nameLabel.textColor = [UIColor colorWithRed:50/255.0 green:153/255.0 blue:50/255.0 alpha:1.0];
    }
    return _nameLabel;
}

-(UIButton*)myDetailBtn
{
    if(_myDetailBtn == nil){
        _myDetailBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-120, self.view.frame.size.height/2, 80, 20)];
        [_myDetailBtn setTitle:@"个人资料" forState:UIControlStateNormal];
        [_myDetailBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [_myDetailBtn addTarget:self action:@selector(goMyDetail) forControlEvents:UIControlEventTouchUpInside];
    }
    return _myDetailBtn;
}

-(UIButton*)myArticleBtn
{
    if(_myArticleBtn == nil){
        _myArticleBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2+40, self.view.frame.size.height/2, 80, 20)];
        [_myArticleBtn setTitle:@"我的帖子" forState:UIControlStateNormal];
        [_myArticleBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [_myArticleBtn addTarget:self action:@selector(goMyArticle) forControlEvents:UIControlEventTouchUpInside];
    }
    return _myArticleBtn;
}

-(UIButton*)myCommentBtn
{
    if(_myCommentBtn == nil){
        _myCommentBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-120, self.view.frame.size.height/2+40, 80, 20)];
        [_myCommentBtn setTitle:@"收到评论" forState:UIControlStateNormal];
        [_myCommentBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [_myCommentBtn addTarget:self action:@selector(goMyComment) forControlEvents:UIControlEventTouchUpInside];
    }
    return _myCommentBtn;
}

-(UIButton*)mySupportBtn
{
    if(_mySupportBtn == nil){
        _mySupportBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2+40, self.view.frame.size.height/2+40, 80, 20)];
        [_mySupportBtn setTitle:@"收到的赞" forState:UIControlStateNormal];
        [_mySupportBtn setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
        [_mySupportBtn addTarget:self action:@selector(goMySupport) forControlEvents:UIControlEventTouchUpInside];
    }
    return _mySupportBtn;
}

-(UIButton*)logoutBtn
{
    if(_logoutBtn == nil){
        _logoutBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width/2-60, self.view.frame.size.height-150, 120, 30)];
        [_logoutBtn setTitle:@"退出登录" forState:UIControlStateNormal];
        [_logoutBtn setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
        [_logoutBtn.titleLabel setFont:[UIFont systemFontOfSize:25]];
        [_logoutBtn addTarget:self action:@selector(logout) forControlEvents:UIControlEventTouchUpInside];
    }
    return _logoutBtn;
}

@end
